package com.qdlc.p2p.biz.adapted;

import java.util.HashMap;
import java.util.Map;

import com.qd.p2p.adapter.AdaptePlatform;
import com.qdlc.p2p.common.util.BeanUtil;

public class AdaptedServiceFactory {

	//获取配置的支付平台
	private static final String PLATFORM = "baofoo";
	
	private static final Map<AdaptedService, AdaptedPayService> adaptedServiceMaps = new HashMap<AdaptedService, AdaptedPayService>();
	
	/**
	 * 获取支付平台适配的服务类
	 * @param adaptedServiceClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends AdaptedPayService> T getService(Class<T> adaptedServiceClass){
		AdaptedService adapted = new AdaptedService(adaptedServiceClass);
		AdaptedPayService adaptedPayService = adaptedServiceMaps.get(adapted);
		if(adaptedPayService == null){
			Map<String, T> maps = BeanUtil.getBeansOfType(adaptedServiceClass);
			for(Map.Entry<String, T> entry: maps.entrySet()){
				adaptedPayService = entry.getValue();
				AdaptePlatform platform =adaptedPayService.supportPlatform();
				if(platform.name().equalsIgnoreCase(PLATFORM)){
					adaptedServiceMaps.put(adapted, adaptedPayService);
					break;
				}
			}
		}
		return (T)adaptedPayService;
	}
	
	
	private static class AdaptedService{
		
		String platform;
		
		Class<? extends AdaptedPayService> adaptedServiceClass;
		
		AdaptedService(Class<? extends AdaptedPayService> adaptedServiceClass){
			this.adaptedServiceClass = adaptedServiceClass;
			this.platform = AdaptedServiceFactory.PLATFORM;
		}
		
		@Override
		public int hashCode() {
			int hashCode = 17;
			hashCode = hashCode * 37 + platform.hashCode();
			hashCode = hashCode * 37 + adaptedServiceClass.hashCode();
			return hashCode;
		}

		@Override
		public boolean equals(Object obj) {
			
			if(obj == this){
				return true;
			}
			
			if(!(obj instanceof AdaptedService)){
				return false;
			}
			
			AdaptedService adapted = (AdaptedService)obj;
			
			return platform.equals(adapted.platform) && adaptedServiceClass.equals(adapted.adaptedServiceClass);
		}
	}
}
